package com.hxzy.controller.admin.dict;

import com.alibaba.excel.EasyExcel;
import com.github.pagehelper.PageInfo;
import com.hxzy.common.annotates.RequiredRole;
import com.hxzy.common.annotates.RequiredRootRole;
import com.hxzy.common.constants.MarketConstants;
import com.hxzy.common.controller.BaseController;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.resp.R;
import com.hxzy.common.util.MarketThreadLocalUtil;
import com.hxzy.controller.admin.dict.req.*;
import com.hxzy.controller.admin.dict.resp.DictTypeResp;
import com.hxzy.controller.admin.employee.req.EmployeeExportIdsReq;
import com.hxzy.controller.admin.employee.req.EmployeeSearchReq;
import com.hxzy.controller.admin.employee.req.EmployeeStatusReq;
import com.hxzy.controller.admin.employee.resp.EmployeeResp;
import com.hxzy.controller.admin.login.resp.AdminLoginResp;
import com.hxzy.entity.SysDictType;
import com.hxzy.mapstruct.DictTypeMapStruct;
import com.hxzy.service.SysDictTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

@Api(tags = "后台-字典管理Api")
@RestController
@RequestMapping(value = "/api/dicttype")
public class DictTypeController extends BaseController {


    @Autowired
    private SysDictTypeService  sysDictTypeService;


    @ApiOperation(value = "分页查询")
    @GetMapping(value = "/data")
    public R<PageInfo<DictTypeResp>> search(@Valid DictTypeReq req ){
        super.startPage(req);
        List<DictTypeResp>  respList=this.sysDictTypeService.search(req);
        return super.buildPageInfo(respList);
    }

    @RequiredRole(role = MarketConstants.ACCOUNT_ADMIN_TYPE)
    @ApiOperation(value = "新增数据")
    @PostMapping
    public R addData(@RequestBody @Valid DictTypeAddReq req){
        boolean result=this.sysDictTypeService.addData(req);
        return result?R.ok(): R.build(AckCode.DATABASE_ERROR);
    }


    @ApiOperation(value = "根据主键查询")
    @GetMapping(value = "/{id}")
    public R<DictTypeResp> findById(@PathVariable(value = "id") Long id){
        if(Objects.isNull(id) || id.intValue()<=0){
            throw new ServiceException(AckCode.SYSTEM_PARAM_FAIL);
        }

        SysDictType db = this.sysDictTypeService.getById(id);
        if(Objects.isNull(db)){
            throw new ServiceException(AckCode.NOT_FOUND_DATA);
        }

        return R.okHasData(DictTypeMapStruct.INSTANCE.convert(db));
    }

    @RequiredRole(role = MarketConstants.ACCOUNT_ADMIN_TYPE)
    @ApiOperation(value = "修改数据")
    @PutMapping
    public R updateData(@RequestBody @Valid DictTypeEditReq req){
        boolean result=this.sysDictTypeService.updateData(req);
        return result?R.ok(): R.build(AckCode.DATABASE_ERROR);
    }

    @RequiredRole(role = MarketConstants.ACCOUNT_ADMIN_TYPE)
    @ApiOperation(value = "更改账户状态")
    @PutMapping(value = "/change/status")
    public R changeStatus(@RequestBody @Valid DictTypeStatusReq req){
        boolean result=this.sysDictTypeService.changeStatus(req);
        return result?R.ok(): R.build(AckCode.DATABASE_ERROR);
    }

    @ApiOperation(value = "导出excel",produces = "application/octet-stream")
    @PostMapping("/download")
    public void download(@RequestBody DictTypeReq req, HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("数据字典", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        //全查询
        List<DictTypeResp> respList = this.sysDictTypeService.search(req);

        //easyexcel最核心的代码
        EasyExcel.write(response.getOutputStream(), DictTypeResp.class).sheet("数据字典").doWrite(respList);
    }

    @ApiOperation(value = "导出excel",produces = "application/octet-stream")
    @PostMapping("/download/choice")
    public void downloadIds(@RequestBody DictTypeExportIdsReq req, HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("数据字典", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        //全查询
        List<DictTypeResp> respList = this.sysDictTypeService.exportExcel(req);

        //easyexcel最核心的代码
        EasyExcel.write(response.getOutputStream(), DictTypeResp.class).sheet("数据字典").doWrite(respList);
    }

}
